package com.example.javalib.math;

//import static java.util.Arrays.binarySearch;

/**
 * @Description:二分查找
 * @author: zcs
 * @email: 1059737741@qq.com
 * create at 2022/2/15 9:35
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] ints = {1, 3, 6, 9, 15, 19, 20};
        System.out.println( binarySearch(ints,19));
    }

    public static int binarySearch (int[] array,int target){
        int low = 0;
        int high = array.length - 1;
        int mid;

        while (low <= high){
            mid = low + (high - low)/2;//(high + low) / 2; //折半下标
            if(array[mid] > target){
                high = mid - 1;
            }else if(array[mid] < target){
                low = mid + 1;
            }else {
                return mid;
            }
        }
        return  -1;
    }
}
